<html>
<head>
    <title>SSE(Server-Sent Events) Chat</title>
    <style>
        span{display: inline}
        input{display: inline}
    </style>
</head>
<body>
<!-- The chat UI is just a single text input field -->
<!-- New chat messages will be inserted before this input field -->
<div id="chatDiv">
    <span id="nickName"></span>
    <input id="input" style="width:80%; padding:10px; border:solid black 2px" />
</div>

<script>
    // Take care of some UI details
    let nick = prompt("Enter your nickname");     // Get user's nickname
    let input = document.getElementById("input"); // Find the input field
    input.focus();                                // Set keyboard focus

    let nickName = document.getElementById("nickName");
    nickName.textContent = nick + ': '

    let chatDiv = document.getElementById("chatDiv");

    // Register for notification of new messages using EventSource
    let chat = new EventSource("/chat");
    // chat.close()
    chat.addEventListener("chatEventXX", event => {  // When a chat message arrives
        let div = document.createElement("div");  // Create a <div>
        div.append(event.data);                   // Add text from the message

        chatDiv.before(div);                        // And add div before input
        chatDiv.scrollIntoView();                   // Ensure input elt is visible
    });

    // Post the user's messages to the server using fetch
    input.addEventListener("change", () => {  // When the user strikes return
        fetch("/chat", {                    // Start an HTTP request to this url.
            method: "POST",                 // Make it a POST request with body
            body: nick + ": " + input.value // set to the user's nick and input.
        }).catch(e => console.error);         // Ignore response, but log any errors.
        input.value = "";                   // Clear the input
    });
</script>
</body>
</html>
